package com.chen.recruit.common.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.hutool.core.util.StrUtil;
import com.chen.recruit.common.api.CommonResult;
import com.chen.recruit.common.constants.MessageConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

/**
 * 全局异常处理
 *
 * @author cgy
 * @date 2022/08/26
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * jsr303 校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult validException(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        return CommonResult.fail(
                e.getBindingResult()
                        .getAllErrors()
                        .stream()
                        .map(DefaultMessageSourceResolvable::getDefaultMessage)
                        .collect(Collectors.joining(StrUtil.LF))
        );
    }

    /**
     * 未登录异常
     */
    @ExceptionHandler(NotLoginException.class)
    public CommonResult notLoginException(NotLoginException e) {
        log.error(e.getMessage(), e);
        return CommonResult.unauthorized();
    }

    /**
     * 无此权限异常
     */
    @ExceptionHandler({NullPointerException.class, NotPermissionException.class})
    public CommonResult noPermissionException(Exception e) {
        log.error(e.getMessage(), e);
        return CommonResult.forbidden();
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public CommonResult sysException(Exception e) {
        log.error(e.getMessage(), e);
        return CommonResult.fail(MessageConstants.UNKNOWN_EXCEPTION);
    }

}
